<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="政策标题" prop="title">
                <el-input v-model="queryParams.title" placeholder="请输入政策标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="修改时间" prop="modifyTime">
                <el-date-picker clearable v-model="queryParams.modifyTime" type="date" value-format="YYYY-MM-DD"
                    placeholder="请选择修改时间">
                </el-date-picker>
            </el-form-item>

            <el-form-item label="过期状态" prop="invalidState">
                <el-select v-model="queryParams.invalidState" placeholder="政策过期状态" clearable style="width:220px;">
                    <el-option v-for="dict in bus_invalid_state" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="政策类型" prop="policyType">
                <el-select v-model="queryParams.policyType" placeholder="请选择政策类型" clearable style="width:220px;">
                    <el-option v-for="dict in sys_policy_type" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>

            <el-form-item label="创建用户" prop="creatorName">
                <el-input v-model="queryParams.creatorName" placeholder="请输入政策创建人的用户名" clearable
                    @keyup.enter="handleQuery" style="width:200px;" />
            </el-form-item>

            <el-form-item label="审核状态" prop="flowStatus">
                <el-select v-model="queryParams.flowStatus" placeholder="请选择审核状态" clearable style="width:220px;">
                    <el-option label="审批中" :value="'1'" />
                    <el-option label="已完成" :value="'8'" />
                    <el-option label="退回" :value="'9'" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd"
                    v-hasPermi="['bus:policy:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
    <el-button 
        type="success" 
        plain 
        icon="Edit" 
        :disabled="single || (currentRow?.flowStatus == 8 || currentRow?.flowStatus == '8')" 
        @click="handleUpdate"
        v-hasPermi="['bus:policy:edit']">
        修改
    </el-button>
</el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple || hasApprovePending"
                    @click="handleDelete" v-hasPermi="['bus:policy:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport"
                    v-hasPermi="['bus:policy:export']">导出</el-button>
            </el-col>
            <el-col :span="1.8">
                <el-button type="primary" plain icon="Document" :disabled="multiple" @click="handleExportSelectedWord"
                    v-hasPermi="['bus:policy:export']">导出Word(所选)</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="policyList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />

            <el-table-column label="政策标题" align="center" prop="title" min-width="150" show-overflow-tooltip />
            <!-- <el-table-column label="政策内容" align="center" prop="content">
                        <template #default="scope">
                            <el-button link type="primary" @click="handleViewDetail(scope.row)">查看详情</el-button>
                        </template>
</el-table-column> -->
            <el-table-column label="政策类型" align="center" prop="policyType" min-width="100">
                <template #default="scope">
                    <dict-tag :options="sys_policy_type" :value="scope.row.policyType" />
                </template>
            </el-table-column>
            <el-table-column label="创建人" align="center" prop="creatorName" min-width="100" />
            <el-table-column label="失效时间" align="center" prop="expirationTime" min-width="120">
                <template #default="scope">
                    <el-tag :type="isExpired(scope.row.expirationTime) ? 'warning' : 'success'" size="small">
                        {{ scope.row.expirationTime ? parseTime(scope.row.expirationTime, '{y}-{m}-{d}') : '无' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="修改时间" align="center" prop="modifyTime" min-width="120">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.modifyTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>

            <el-table-column label="过期状态" align="center" prop="invalidState" min-width="100">
                <!-- <template v-slot="{ row }">
          <dict-tag :options="[
            { label: '失效', value: '1' },
            { label: '正常', value: '0' }
          ]" :value="row.invalidState" />
        </template> -->
                <template #default="scope">
                    <dict-tag :options="bus_invalid_state" :value="scope.row.invalidState" />
                </template>
            </el-table-column>

            <el-table-column label="审核状态" align="center" prop="flowStatus" min-width="100">
                <!-- <template v-slot="{ row }">
          <dict-tag :options="[
            { label: '待审核', value: '1' },
            { label: '已通过', value: '0' },
            { label: '驳回', value: '2' }
          ]" :value="row.approveStatus" />
        </template> -->
                <template #default="scope">
                    <dict-tag :options="flow_status" :value="scope.row.flowStatus" />
                </template>
            </el-table-column>


            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="180">
                <template #default="scope">
                    <el-button link type="primary" @click="handleViewDetail(scope.row)"
                        style="margin-right: 5px;">查看详情</el-button>
                    <el-button v-if="scope.row.flowStatus != 8 && scope.row.flowStatus != '8'" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['bus:policy:edit']" style="margin-right: 5px;">修改</el-button>
                    <el-button v-if="scope.row.flowStatus != 1 && scope.row.flowStatus != '1'" link type="primary"
                        icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['bus:policy:remove']">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="true" :total="Number(total)" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改政策内容对话框 -->
        <el-dialog :title="title" v-model="open" width="800px" append-to-body>
            <el-form ref="policyRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="政策标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入政策标题" :maxlength="120" show-word-limit
                        @input="handleTitleInput" @keydown="handleTitleKeydown"
                        @compositionend="handleTitleCompositionEnd" />
                </el-form-item>
                <el-form-item label="政策内容">
                    <div class="editor-container">

                        <div class="editor-content rich-text-content" contenteditable="true" @input="handleEditorInput"
                            ref="editorRef"></div>
                    </div>
                    <div class="word-count-tip" :class="{ 'warning': getContentCharCount() > 18000 }">
                        当前字符数：{{ getContentCharCount() }} / 120000
                    </div>
                </el-form-item>

                <el-form-item label="失效时间" prop="expirationTime">
                    <el-date-picker clearable v-model="form.expirationTime" type="date" value-format="YYYY-MM-DD"
                        placeholder="请选择失效时间">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="政策类型" prop="policyType">
                    <el-select v-model="form.policyType" placeholder="请选择政策类型">
                        <el-option v-for="dict in sys_policy_type" :key="dict.value" :label="dict.label"
                            :value="parseInt(dict.value)"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 政策内容详情对话框 -->
        <el-dialog :title="detailTitle" v-model="detailOpen" width="800px" append-to-body>
            <div class="detail-info">
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="创建人">{{ detailInfo.creatorName || '暂无' }}</el-descriptions-item>
                    <el-descriptions-item label="政策类型">
                        <dict-tag :options="sys_policy_type" :value="detailInfo.policyType" />
                    </el-descriptions-item>
                    <el-descriptions-item label="过期时间">
                        {{ detailInfo.expirationTime ? parseTime(detailInfo.expirationTime, '{y}-{m}-{d}') : '暂无' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="创建时间">
                        {{ detailInfo.createTime ? parseTime(detailInfo.createTime, '{y}-{m}-{d} {h}:{i}:{s}') : '暂无' }}
                    </el-descriptions-item>
                </el-descriptions>
            </div>
            <div class="detail-content">
                <div class="content-title">政策内容：</div>
                <div v-html="detailContent" class="rich-text-content"></div>
            </div>

            <!-- 审批意见 -->
            <div class="approval-comment" v-if="detailInfo.comment">
                <div class="content-title">
                    <i class="el-icon-document-checked"></i>
                    审批意见
                </div>
                <div class="comment-content">
                    <div class="comment-card">
                        <div class="comment-header">
                            <span class="comment-label">审批人意见</span>
                            <el-tag type="info" size="small">审批记录</el-tag>
                        </div>
                        <div class="comment-body">
                            <div class="comment-text">{{ detailInfo.comment }}</div>
                        </div>
                    </div>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="detailOpen = false">关 闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Policy">
import { listPolicy, getPolicy, delPolicy, addPolicy, updatePolicy } from "@/api/bus/policy";
import { computed, nextTick, ref, reactive, toRefs, getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance();
const { sys_policy_type } = proxy.useDict('sys_policy_type');
const { bus_invalid_state } = proxy.useDict('bus_invalid_state');
const { flow_status } = proxy.useDict('flow_status');

const policyList = ref([]);
const open = ref(false);
const detailOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const detailTitle = ref("");
const detailContent = ref("");
const detailInfo = ref({});


const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        content: null,
        expirationTime: null,
        modifyTime: null,
        delTime: null,
        invalidState: null,
        policyType: null,
        flowStatus: null,
        creatorId: null,
        creatorName: null
    },
    rules: {
        title: [
            { required: true, message: "政策标题不能为空", trigger: "blur" },
            { max: 120, message: "政策标题不能超过120个字符", trigger: "blur" }
        ],
        content: [
            { required: true, message: "政策内容不能为空", trigger: "blur" },
            {
                validator: (rule, value, callback) => {
                    if (value) {
                        const plainText = stripHtml(value);
                        if (plainText.length > 120000) {
                            callback(new Error("政策内容不能超过120000个字符"));
                        } else {
                            callback();
                        }
                    } else {
                        callback();
                    }
                },
                trigger: "blur"
            }
        ],
        expirationTime: [
            { required: false, message: "失效时间不能为空", trigger: "change" }
        ],
        policyType: [
            { required: true, message: "政策类型不能为空", trigger: "change" }
        ]
    }
});

const { queryParams, form, rules } = toRefs(data);

const hasApprovePending = computed(() =>
    policyList.value
      .filter(item => ids.value.includes(item.policyId))
      .some(item => item.flowStatus == 1 || item.flowStatus == '1')
);

function stripHtml(html) {
    if (!html) return '';

    // 创建临时DOM元素来解析HTML
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = html;

    // 获取纯文本内容
    let text = tempDiv.textContent || tempDiv.innerText || '';

    // 去除换行符和多余空格
    text = text.replace(/\r\n/g, '').replace(/\n/g, '').replace(/\r/g, '');
    // 去除多余空格
    text = text.replace(/\s+/g, ' ').trim();

    return text;
}

/** 处理标题输入，限制字符数 */
function handleTitleInput(value) {
    if (!value) {
        return;
    }

    // 如果超过120个字符，阻止输入并恢复原值
    if (value.length > 120) {
        // 阻止输入，恢复到之前的值
        form.value.title = value.substring(0, 120);
        // 显示提示信息
        proxy.$modal.msgError("标题不能超过120个字符");
        return;
    }
}

/** 处理标题键盘事件，进一步限制输入 */
function handleTitleKeydown(event) {
    const currentValue = form.value.title || '';

    // 如果当前长度已经达到120，阻止大部分输入
    if (currentValue.length >= 120) {
        // 允许删除键、方向键等
        const allowedKeys = ['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Tab', 'Enter'];
        if (!allowedKeys.includes(event.key)) {
            event.preventDefault();
            proxy.$modal.msgError("标题已达到最大长度限制");
            return false;
        }
    }
}

/** 处理输入法输入结束事件 */
function handleTitleCompositionEnd(event) {
    const value = event.target.value;
    if (value && value.length > 120) {
        // 截取前120个字符
        form.value.title = value.substring(0, 120);
        proxy.$modal.msgError("标题不能超过120个字符");
    }
}

/** 处理编辑器输入 */
function handleEditorInput(event) {
    const content = event.target.innerHTML;
    form.value.content = content;

    // 字符数限制
    const plainText = stripHtml(content);
    if (plainText.length > 120000) {
        proxy.$modal.msgError("政策内容不能超过120000个字符");
        // 恢复到之前的内容
        event.target.innerHTML = form.value.content;
        return;
    }
}

/** 处理格式化 */
function handleFormat(command) {
    document.execCommand(command, false, null);
    proxy.$refs.editorRef.focus();
}

/** 获取内容字符数 */
function getContentCharCount() {
    if (!form.value.content) {
        return 0;
    }
    return stripHtml(form.value.content).length;
}

/** 查询政策内容列表 */
function getList() {
    loading.value = true;
    listPolicy(queryParams.value).then(response => {
        console.log('API响应数据:', response);
        policyList.value = response.rows;
        // 确保total是数字类型
        total.value = Number(response.total);
        console.log('total值:', total.value, '类型:', typeof total.value);
        loading.value = false;
    }).catch(error => {
        console.error('请求失败:', error);
        loading.value = false;
    });
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        policyId: null,
        title: null,
        content: null,
        expirationTime: null,
        createTime: null,
        modifyTime: null,
        delTime: null,
        invalidState: null,
        policyType: null,
        flowStatus: null
        // creatorId 和 creatorName 由后端自动设置
    };
    proxy.resetForm("policyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.policyId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加政策内容";

}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const _policyId = row.policyId || ids.value
    getPolicy(_policyId).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改政策内容";
        // 在下一个tick中设置编辑器内容，确保DOM已更新
        nextTick(() => {
            if (form.value.content) {
                proxy.$refs.editorRef.innerHTML = form.value.content;
            }
        });
    });
}

/** 查看详情按钮操作 */
function handleViewDetail(row) {
    detailTitle.value = row.title;
    detailContent.value = row.content || '';
    detailInfo.value = {
        creatorName: row.creatorName,
        policyType: row.policyType,
        expirationTime: row.expirationTime,
        createTime: row.createTime,
        comment: row.comment // 直接从政策内容中获取审批意见
    };

    detailOpen.value = true;
}

/** 提交按钮 */
function submitForm() {
    // 额外验证标题长度
    if (form.value.title && form.value.title.length > 120) {
        proxy.$modal.msgError("标题不能超过120个字符");
        return;
    }

    // 额外验证内容长度
    if (form.value.content) {
        const plainText = stripHtml(form.value.content);
        if (plainText.length > 120000) {
            proxy.$modal.msgError("政策内容不能超过120000个字符");
            return;
        }
    }

    // 检查失效时间是否为空，如果为空则询问用户是否确定
    if (!form.value.expirationTime) {
        proxy.$modal.confirm('失效时间为空，是否确定继续提交？').then(() => {
            // 用户确认，继续提交
            submitFormData();
        }).catch(() => {
            // 用户取消，不提交
            return;
        });
    } else {
        // 失效时间不为空，直接提交
        submitFormData();
    }
}

/** 实际提交表单数据 */
function submitFormData() {
    proxy.$refs["policyRef"].validate(valid => {
        if (valid) {
            if (form.value.policyId != null) {
                updatePolicy(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addPolicy(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _policyIds = row.policyId || ids.value;
    proxy.$modal.confirm('是否确认删除政策内容编号为"' + _policyIds + '"的数据项？').then(function () {
        return delPolicy(_policyIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download('bus/policy/export', {
        ...queryParams.value
    }, `policy_${new Date().getTime()}.xlsx`)
}

/** 导出所选为Word */
function handleExportSelectedWord() {
    if (!ids.value || ids.value.length === 0) {
        proxy.$modal.msgError('请先选择要导出的数据');
        return;
    }
    // 逐个下载，文件名为 policy_id.docx
    ids.value.forEach((pid) => {
        proxy.download(`bus/policy/exportWord/${pid}`, {}, `${pid}.docx`)
    });
}

// flowStatus 由字典 flow_status 渲染，不再需要手工映射

/** 判断是否过期 */
function isExpired(expirationTime) {
    if (!expirationTime) {
        return false;
    }
    const currentTime = new Date();
    const expirationDate = new Date(expirationTime);
    return expirationDate < currentTime;
}



getList();
</script>

<style scoped>
.content-ellipsis {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    max-width: 300px;
}

.detail-content {
    max-height: 500px;
    overflow-y: auto;
    padding: 10px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background-color: #fafafa;
}

.editor-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
    width: 800px;
    max-width: 800px;
}

.editor-toolbar {
    padding: 8px;
    border-bottom: 1px solid #dcdfe6;
    background-color: #f5f7fa;
}

.editor-content {
    min-height: 192px;
    padding: 12px;
    outline: none;
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;
}

.rich-text-content {
    line-height: 1.8;
    word-wrap: break-word;
    white-space: pre-wrap;
    font-size: 14px;
    color: #333;
}

.rich-text-content p {
    margin: 0 0 15px 0;
    text-indent: 2em;
    line-height: 1.8;
}

.rich-text-content h1,
.rich-text-content h2,
.rich-text-content h3,
.rich-text-content h4,
.rich-text-content h5,
.rich-text-content h6 {
    margin: 20px 0 15px 0;
    font-weight: bold;
    line-height: 1.4;
}

.rich-text-content h1 {
    font-size: 24px;
}

.rich-text-content h2 {
    font-size: 20px;
}

.rich-text-content h3 {
    font-size: 18px;
}

.rich-text-content h4 {
    font-size: 16px;
}

.rich-text-content h5 {
    font-size: 14px;
}

.rich-text-content h6 {
    font-size: 12px;
}

.rich-text-content ul,
.rich-text-content ol {
    margin: 15px 0;
    padding-left: 30px;
}

.rich-text-content li {
    margin: 8px 0;
    line-height: 1.6;
}

.rich-text-content blockquote {
    margin: 15px 0;
    padding: 15px 20px;
    border-left: 4px solid #409eff;
    background-color: #f5f7fa;
    font-style: italic;
    border-radius: 4px;
}

.rich-text-content table {
    width: 100%;
    border-collapse: collapse;
    margin: 15px 0;
    border: 1px solid #dcdfe6;
}

.rich-text-content th,
.rich-text-content td {
    border: 1px solid #dcdfe6;
    padding: 10px 12px;
    text-align: left;
    vertical-align: top;
}



.rich-text-content th {
    background-color: #f5f7fa;
    font-weight: bold;
}

.rich-text-content img {
    max-width: 100%;
    height: auto;
    margin: 15px 0;
    border-radius: 4px;
}

.rich-text-content a {
    color: #409eff;
    text-decoration: none;
}

.rich-text-content a:hover {
    text-decoration: underline;
}

.rich-text-content div {
    margin: 10px 0;
}

.rich-text-content br {
    display: block;
    margin: 5px 0;
}

.word-count-tip {
    margin-top: 5px;
    font-size: 12px;
    color: #909399;
    text-align: right;
}

.word-count-tip.warning {
    color: #e6a23c;
    font-weight: bold;
}

.detail-info {
    margin-bottom: 20px;
}

.content-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 1px solid #e4e7ed;
}

/* 审批意见区域 */
.approval-comment {
    margin-top: 24px;
    border-top: 1px solid #f0f0f0;
    padding-top: 20px;
}

.approval-comment .content-title {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 16px;
}

.approval-comment .content-title i {
    margin-right: 8px;
    color: #409EFF;
    font-size: 18px;
}

.comment-content {
    margin-top: 12px;
}

.comment-card {
    background: #fafafa;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.comment-header {
    background: #f5f7fa;
    padding: 12px 16px;
    border-bottom: 1px solid #e4e7ed;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.comment-label {
    font-size: 14px;
    font-weight: 500;
    color: #606266;
}

.comment-body {
    padding: 16px;
    background: #ffffff;
}

.comment-text {
    color: #303133;
    line-height: 1.6;
    font-size: 14px;
    word-break: break-word;
    white-space: pre-wrap;
    margin: 0;
    min-height: 20px;
}
</style>